<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\TempleSetting;
use think\facade\Db;

/**
 * @extends Service<TempleSettingService>
 */
class TempleSettingService extends Service
{
    public function list($page, $limit, $searchQuery = null)
    {
        $w = [];
        $w[] = ['is_delete', '=', 0];
        if (!empty($searchQuery['temple_id']) && $searchQuery['temple_id'] != '') {
            $w['temple_id'] = $searchQuery['temple_id'];
        }
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w['type'] = $searchQuery['type'];
        }
        $map = TempleSetting::where($w)->page($page, $limit)->order('day_num asc');
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    public function save($data, $id = null)
    {
        Db::startTrans();
        try {
            if (empty($id)) {
                $temple_ids = explode(',', $data['temple_id']);
                $temple_ids = array_unique($temple_ids);
                if ($temple_ids) {
                    foreach ($temple_ids as $temple_id) {
                        TempleSetting::where([
                            'temple_id' => $temple_id, 'type' => $data['type'], 'day_num' => $data['day_num']
                        ])->delete();
                        TempleSetting::create([
                            'temple_id' => $temple_id,
                            'type' => $data['type'],
                            'day_num' => $data['day_num'],
                            'amount' => $data['amount']
                        ]);
                    }
                }
            } else {
                $info = TempleSetting::where('id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save([
                    'temple_id' => $data['temple_id'],
                    'type' => $data['type'],
                    'day_num' => $data['day_num'],
                    'amount' => $data['amount']
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function info($id)
    {
        $info = TempleSetting::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }

        return $info->toArray();
    }


    public function del($id)
    {
        $info = TempleSetting::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->save(['is_delete' => 1]);
    }

}